package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.view.View;

public class CuteTimerButton extends CuteButton implements View.OnClickListener {

    private static final int DEFAULT_TIME_COUNT = 60;

    private static final int DEFAULT_SLEEP_TIME = 1000;

    private int timeCount = DEFAULT_TIME_COUNT;

    private int sleepTime = DEFAULT_SLEEP_TIME;

    private CountDownTimer mCountDownTimer;

    public interface TimerListener {

        void timerStart(View v, int startCount);

        void timerCount(View v, int currentCount);

        void timerEnd(View v);

    }

    private TimerListener timerListener;

    public CuteTimerButton(Context context) {
        super(context);
    }

    public CuteTimerButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CuteTimerButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

    @Override
    public void onClick(View v) {
        if (timerListener != null && timeCount > 0) {
            timerListener.timerStart(v, timeCount);
            setClickable(false);
            // 计时器
            mCountDownTimer = new CountDownTimer(timeCount * sleepTime, sleepTime) {

                @Override
                public void onTick(long millisUntilFinished) {
                    timerListener.timerCount(CuteTimerButton.this, (int) millisUntilFinished / DEFAULT_SLEEP_TIME);
                }

                @Override
                public void onFinish() {
                    setClickable(true);
                    timerListener.timerEnd(CuteTimerButton.this);
                }
            };
            mCountDownTimer.start();
        }
    }

    /**
     * 设置计数监听器
     */
    public void setTimerListener(TimerListener timerListener) {
        setOnClickListener(this);
        this.timerListener = timerListener;
    }

    /**
     * 设置计数
     */
    public void setTimeCount(int timeCount) {
        this.timeCount = timeCount;
    }

    public int getTimeCount() {
        return timeCount;
    }

    /**
     * 设置休眠时间
     */
    public void setSleepTime(int sleepTime) {
        this.sleepTime = sleepTime;
    }

    public int getSleepTime() {
        return sleepTime;
    }

    public void stop() {
        if(mCountDownTimer != null) {
            mCountDownTimer.cancel();
        }
    }

}
